package repository

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/forum/model"

	"github.com/sirupsen/logrus"
	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"
	"github.com/zeromicro/go-zero/core/stores/cache"
)

type (
	// CommentRepository is an interface to be customized, add more methods here,
	// and implement the added methods in customCommentRepository.
	CommentRepository interface {
		FindOne(ctx context.Context, id uint64) (*model.ForumComment, error)
		FindOneWithExpire(
			ctx context.Context,
			id uint64,
			expire time.Duration,
		) (*model.ForumComment, error)
		FindOneNoCache(
			ctx context.Context,
			conn boil.ContextExecutor,
			id uint64,
		) (*model.ForumComment, error)
		GetList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ForumComment, int64, error)
		Insert(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.ForumComment,
			meta []*model.ForumCommentMetum,
		) error
		Update(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.ForumComment,
			meta []*model.ForumCommentMetum,
		) error
		UpdateBatch(
			ctx context.Context,
			tx boil.ContextExecutor,
			ids []uint64,
			cols model.M,
			meta []*model.ForumCommentMetum,
		) error
		SoftDelete(ctx context.Context, tx boil.ContextExecutor, id uint64) error
		Restore(ctx context.Context, tx boil.ContextExecutor, id uint64) error
		GetMeta(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.ForumCommentMetum, int64, error)
		InsertMeta(
			ctx context.Context,
			tx boil.ContextExecutor,
			meta []*model.ForumCommentMetum,
		) error
	}

	customCommentRepository struct {
		modelx.CachedConn
		mysqlConn           *sql.DB
		cacheIdPrefix       string
		cacheIdExpirePrefix string
	}
)

// NewCommentRepository returns a repository for the database table.
func NewCommentRepository(mysqlConn *sql.DB, cacheConf cache.CacheConf) CommentRepository {
	return &customCommentRepository{
		CachedConn:          modelx.NewConn(mysqlConn, cacheConf),
		mysqlConn:           mysqlConn,
		cacheIdPrefix:       "cache:forum:comment:id:",
		cacheIdExpirePrefix: "cache:forum:comment:id:expire:",
	}
}

func (r *customCommentRepository) FindOne(
	ctx context.Context,
	id uint64,
) (*model.ForumComment, error) {
	cacheIdKey := r.formatPrimary(id)
	var resp model.ForumComment
	err := r.QueryCtx(ctx, &resp, cacheIdKey, func(ctx context.Context, conn *sql.DB, v any) error {
		data, err := model.FindForumComment(ctx, conn, id)
		if err != nil {
			return err
		}

		*v.(*model.ForumComment) = *data
		return nil
	})

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customCommentRepository) FindOneWithExpire(
	ctx context.Context,
	id uint64,
	expire time.Duration,
) (*model.ForumComment, error) {
	cacheIdKey := r.formatPrimary(id)
	var resp model.ForumComment
	err := r.QueryWithExpireCtx(ctx, &resp, cacheIdKey, expire, func(ctx context.Context, conn *sql.DB, v any) error {
		data, err := model.FindForumComment(ctx, conn, id)
		if err != nil {
			return err
		}

		*v.(*model.ForumComment) = *data

		return nil
	})

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customCommentRepository) FindOneNoCache(
	ctx context.Context,
	conn boil.ContextExecutor,
	id uint64,
) (*model.ForumComment, error) {
	var db boil.ContextExecutor = r.mysqlConn
	if conn != nil {
		db = conn
	}
	data, err := model.FindForumComment(ctx, db, id)
	logrus.Info(fmt.Sprintf("FindOneNoCache err: %+v", err))
	switch err {
	case nil:
		return data, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customCommentRepository) GetList(
	ctx context.Context,
	cols model.M,
	withCount int, // -1-返回list；0-返回count；1-返回count和list；2-根据offset返回count和list；3-根据preMinId返回count和list；4-根据preMaxId返回count和list
	filter map[string]map[string][]any,
) (list []*model.ForumComment, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumCommentColumns.PostID+" DESC"))
					mods = append(mods, model.ForumCommentWhere.PostID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumCommentColumns.PostID+" ASC"))
					mods = append(mods, model.ForumCommentWhere.PostID.GT(val))
					previousCount = 1
				}
			}
		case "orderBy":
			if withCount != 3 && withCount != 4 {
				if val, ok := v.(string); ok && val != "" {
					mods = append(mods, qm.OrderBy(val))
				}
			}
		case "select":
			if val, ok := v.(string); ok && val != "" {
				selectCol = val
			}
		}
	}

	if filter != nil {
		for key, opMap := range filter {
			switch key {
			case model.ForumCommentColumns.CommentID:
				mods = append(mods, modelx.GetIntMods(model.ForumCommentColumns.CommentID, opMap)...)
			case model.ForumCommentColumns.ForumID:
				mods = append(mods, modelx.GetIntMods(model.ForumCommentColumns.ForumID, opMap)...)
			case model.ForumCommentColumns.TopicID:
				mods = append(mods, modelx.GetIntMods(model.ForumCommentColumns.TopicID, opMap)...)
			case model.ForumCommentColumns.PostID:
				mods = append(mods, modelx.GetIntMods(model.ForumCommentColumns.PostID, opMap)...)
			case model.ForumCommentColumns.ParentID:
				mods = append(mods, modelx.GetIntMods(model.ForumCommentColumns.ParentID, opMap)...)
			case model.ForumCommentColumns.CommentUserID:
				mods = append(mods, modelx.GetIntMods(model.ForumCommentColumns.CommentUserID, opMap)...)
			case model.ForumCommentColumns.CommentUser:
				mods = append(mods, modelx.GetStringMods(model.ForumCommentColumns.CommentUser, opMap)...)
			case model.ForumCommentColumns.CommentUserEmail:
				mods = append(mods, modelx.GetStringMods(model.ForumCommentColumns.CommentUserEmail, opMap)...)
			case model.ForumCommentColumns.CommentUserURL:
				mods = append(mods, modelx.GetStringMods(model.ForumCommentColumns.CommentUserURL, opMap)...)
			case model.ForumCommentColumns.CommentUserIP:
				mods = append(mods, modelx.GetStringMods(model.ForumCommentColumns.CommentUserIP, opMap)...)
			case model.ForumCommentColumns.CommentUserAnonymous:
				mods = append(mods, modelx.GetIntMods(model.ForumCommentColumns.CommentUserAnonymous, opMap)...)
			case model.ForumCommentColumns.CommentContent:
				mods = append(mods, modelx.GetStringMods(model.ForumCommentColumns.CommentContent, opMap)...)
			case model.ForumCommentColumns.CommentType:
				mods = append(mods, modelx.GetIntMods(model.ForumCommentColumns.CommentType, opMap)...)
			case model.ForumCommentColumns.CommentStatus:
				mods = append(mods, modelx.GetIntMods(model.ForumCommentColumns.CommentStatus, opMap)...)
			case model.ForumCommentColumns.DelStatus:
				mods = append(mods, modelx.GetIntMods(model.ForumCommentColumns.DelStatus, opMap)...)
			case model.ForumCommentColumns.Sticky:
				mods = append(mods, modelx.GetIntMods(model.ForumCommentColumns.Sticky, opMap)...)
			case model.ForumCommentColumns.CommentDate:
				mods = append(mods, modelx.GetStringMods(model.ForumCommentColumns.CommentDate, opMap)...)
			}
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.ForumComments(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}

		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	} else {
		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		} else {
			columns = append(columns, model.ForumCommentColumns.CommentID)
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ForumComments(mods...).All(ctx, r.mysqlConn)
	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customCommentRepository) Insert(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.ForumComment,
	meta []*model.ForumCommentMetum,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		err := data.Insert(ctx, db, boil.Infer())
		if err != nil {
			return err
		}

		commentId := data.CommentID
		if len(meta) > 0 {
			for _, v := range meta {
				v.CommentID = commentId
				err = v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}
func (r *customCommentRepository) InsertMeta(
	ctx context.Context,
	tx boil.ContextExecutor,
	meta []*model.ForumCommentMetum,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}
		if len(meta) > 0 {
			for _, v := range meta {
				err := v.Insert(ctx, db, boil.Infer())
				if err != nil {
					return err
				}
			}
		}
		return nil
	})
	return err
}
func (r *customCommentRepository) Update(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.ForumComment,
	meta []*model.ForumCommentMetum,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Blacklist(
			model.ForumCommentColumns.CommentID,
			model.ForumCommentColumns.ForumID,
			model.ForumCommentColumns.PostID,
			model.ForumCommentColumns.ParentID,
			model.ForumCommentColumns.CommentUserID,
			model.ForumCommentColumns.CommentContent,
			model.ForumCommentColumns.CommentDate,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		commentId := data.CommentID
		if len(meta) > 0 {
			for _, v := range meta {
				if v.MetaID > 0 {
					_, err = v.Update(ctx, db, boil.Blacklist(
						model.ForumCommentMetumColumns.MetaID,
						model.ForumCommentMetumColumns.CommentID,
						model.ForumCommentMetumColumns.MetaKey,
					))
					if err != nil {
						return err
					}
				} else {
					v.CommentID = commentId
					err = v.Insert(ctx, db, boil.Infer())
					if err != nil {
						return err
					}
				}
			}
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCommentRepository) UpdateBatch(
	ctx context.Context,
	tx boil.ContextExecutor,
	ids []uint64,
	cols model.M,
	meta []*model.ForumCommentMetum,
) error {
	if len(ids) > 0 {
		err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
			var db boil.ContextExecutor
			if tx != nil {
				db = tx
			} else {
				db = conn
			}

			var mods []qm.QueryMod
			mods = append(mods, model.ForumCommentWhere.PostID.IN(ids))

			rowsAff, err := model.ForumComments(mods...).UpdateAll(ctx, db, cols)
			if err != nil {
				return err
			}

			if rowsAff == 0 {
				return model.ErrNotUpdated
			}

			if len(meta) > 0 {
				for _, v := range meta {
					err = v.Insert(ctx, db, boil.Infer())
					if err != nil {
						return err
					}
				}
			}

			return nil
		}, r.formatPrimaries(ids)...)

		return err
	}

	return nil
}

func (r *customCommentRepository) SoftDelete(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.CommentStatus == uint8(globalkey.StatusDeleted) {
		return nil
	}

	data.DelStatus = data.CommentStatus
	data.CommentStatus = uint8(globalkey.StatusDeleted)

	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Blacklist(
			model.ForumCommentColumns.PostID,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCommentRepository) Restore(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.CommentStatus != uint8(globalkey.StatusDeleted) {
		return nil
	}

	data.CommentStatus = data.DelStatus

	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Blacklist(
			model.ForumCommentColumns.PostID,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCommentRepository) getCacheKeys(data *model.ForumComment) []string {
	if data == nil {
		return []string{}
	}

	cacheIdKey := r.formatPrimary(data.PostID)
	cacheKeys := []string{
		cacheIdKey,
	}

	return cacheKeys
}

func (r *customCommentRepository) formatPrimary(primary any) string {
	return fmt.Sprintf("%s%v", r.cacheIdPrefix, primary)
}

func (r *customCommentRepository) formatPrimaries(primaries []uint64) []string {
	var resp []string
	for _, primary := range primaries {
		resp = append(resp, r.formatPrimary(primary))
	}

	return resp
}

func (r *customCommentRepository) queryPrimary(ctx context.Context, conn *sql.DB, v, primary any) error {
	var pid uint64
	if jsonId, ok := primary.(json.Number); ok {
		if int64Id, err := jsonId.Int64(); err == nil {
			pid = uint64(int64Id)
		} else {
			return err
		}
	}

	data, err := model.FindForumComment(ctx, conn, pid)
	if err != nil {
		return err
	}

	*v.(*model.ForumComment) = *data

	return nil
}

func (r *customCommentRepository) GetMeta(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.ForumCommentMetum, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumCommentMetumColumns.MetaID+" DESC"))
					mods = append(mods, model.ForumCommentMetumWhere.MetaID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.ForumCommentMetumColumns.MetaID+" ASC"))
					mods = append(mods, model.ForumCommentMetumWhere.MetaID.GT(val))
					previousCount = 1
				}
			}
		case "orderBy":
			if withCount != 3 && withCount != 4 {
				if val, ok := v.(string); ok && val != "" {
					mods = append(mods, qm.OrderBy(val))
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && val != "" {
					selectCol = val
				}
			}
		}
	}

	if filter != nil {
		for key, opMap := range filter {
			switch key {
			case model.ForumCommentMetumColumns.MetaID:
				mods = append(mods, modelx.GetIntMods(model.ForumCommentMetumColumns.MetaID, opMap)...)
			case model.ForumCommentMetumColumns.CommentID:
				mods = append(mods, modelx.GetIntMods(model.ForumCommentMetumColumns.CommentID, opMap)...)
			case model.ForumCommentMetumColumns.MetaKey:
				mods = append(mods, modelx.GetStringMods(model.ForumCommentMetumColumns.MetaKey, opMap)...)
			}
		}
	}

	if withCount >= 2 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.ForumCommentMeta(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}

		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	} else {
		if pageSize > 0 {
			if page > 1 {
				mods = append(mods, qm.Offset(pageSize*(page-1)))
			}
			mods = append(mods, qm.Limit(pageSize))
		}
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		} else {
			columns = append(columns, model.ForumCommentMetumColumns.MetaID)
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.ForumCommentMeta(mods...).All(ctx, r.mysqlConn)
	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}
